package com.wtgroup.demo.leetcode.q042_接雨水;

public class Q042_LC_DP {


    /**
     * 动态规划
     *
     * 每个位置左边最大和右边最大
     * [答案]
     */
    public int trap(int[] height) {
        int n = height.length;
        if (n < 3) {
            return 0;
        }
        int[] leftMax = new int[n];
        int[] rightMax = new int[n];
        leftMax[0] = height[0];
        for (int i = 1; i < n-1; i++) {
            leftMax[i] = Math.max(height[i], leftMax[i - 1]);
        }
        rightMax[n - 1] = height[n - 1];
        for (int i = n-2; i > 0; i--) {
            rightMax[i] = Math.max(height[i], rightMax[i + 1]);
        }

        int area = 0;
        for (int i = 1; i < n-1; i++) {
            area += Math.min(leftMax[i], rightMax[i]) - height[i];
        }

        return area;
    }

}
